package com.ffapp.demo.common;

import android.app.Activity;
import android.graphics.Color;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.ffapp.demo.R;
import com.ffapp.demo.bean.ParamsEditItemData;
import com.ffapp.demo.bean.ParamsEditListBean;
import com.ffapp.demo.bean.ProvinceListBean;
import com.suke.widget.SwitchButton;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.CheckUtils;
import my.IntentUtils;
import my.LogUtil;
import my.StringUtil;
import my.ViewUtils;

public class AdapterCommonListEdit extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    boolean isStopChange = false;
    boolean isEdit = true;

    Activity mContext;
    ParamsEditListBean mListBean;
    int adapter_position;
    int divider_magin_left = 0;
    int divider_magin_right = 0;

    public AdapterCommonListEdit(Activity activity, int position, ParamsEditListBean listBean, boolean isEdit) {
        mContext = activity;
        this.adapter_position = position;
        this.mListBean = listBean;
        this.isEdit = isEdit;
    }

    public AdapterCommonListEdit(Activity activity, ParamsEditListBean listBean) {
        mContext = activity;
        this.mListBean = listBean;
        this.isEdit = false;
    }

    public void setData(ParamsEditListBean listBean,boolean isEdit) {
        this.isEdit = isEdit;
        this.mListBean = listBean;
        notifyDataSetChanged();
    }
    public void setDividerMargin(int left,int right){
        this.divider_magin_left = left;
        this.divider_magin_right = right;
    }

    public void onEditChange(boolean isEdit){
        this.isEdit = isEdit;
        notifyDataSetChanged();
    }

    //创建新View，被LayoutManager所调用
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.common_detail_edit_list_item, viewGroup, false);
        return new AdapterCommonListEdit.ViewHolder(view);
    }

    //将数据与界面进行绑定的操作
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        ((ViewHolder) viewHolder).bind(position);
    }

    //        @Override
//        public void onBindViewHolder(@NonNull ViewHolder holder, int position, @NonNull List<Object> payloads) {
//            super.onBindViewHolder(holder, position, payloads);
//
//        }

    //获取数据的数量
    @Override
    public int getItemCount() {
        return mListBean == null ? 0 : mListBean.getList().size();
    }

    //自定义的ViewHolder，持有每个Item的的所有界面元素
    public class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.list_item)
        public View list_item;
        @BindView(R.id.text_name)
        public TextView text_name;
        @BindView(R.id.text_name_des)
        public TextView text_name_des;
        @BindView(R.id.edit_content)
        public EditText edit_content;
        @BindView(R.id.view_edit_zone)
        public View view_edit_zone;
        @BindView(R.id.view_text_zone)
        public View view_text_zone;
        @BindView(R.id.text_content)
        public TextView text_content;
        @BindView(R.id.text_title)
        public TextView text_title;
        @BindView(R.id.text_unit)
        public TextView text_unit;
        @BindView(R.id.view_item_title_zone)
        public View view_item_title_zone;
        @BindView(R.id.view_item_data_zone)
        public View view_item_data_zone;
        @BindView(R.id.view_big_name_zone)
        public View view_big_name_zone;
        @BindView(R.id.view_name_zone)
        public View view_name_zone;
        @BindView(R.id.img_tag)
        public ImageView img_tag;
        @BindView(R.id.img_tag_edit)
        public ImageView img_tag_edit;
        @BindView(R.id.btn_switch)
        public SwitchButton btn_switch;
        @BindView(R.id.img_star_edit)
        public TextView img_star_edit;
        @BindView(R.id.text_name_big)
        public TextView text_name_big;
        @BindView(R.id.img_divider_hor)
        public ImageView img_divider_hor;
        @BindView(R.id.img_icon_call)
        public ImageView img_icon_call;

        public ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
            btn_switch.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                    int position = (int) view.getTag();
                    mListBean.onChildItemBooleanChange(position);
//                        LogUtil.i("onCheckedChanged--->"+isChecked+"--->"+mListBean.getList().get(position).getValue());
                    stopChangeAndNofyDataSetChanged();
//                        LogUtil.i("onBoolean setOnCheckedChangeListener----->"+   StringUtil.Str2Boolean(mListBean.getList().get(position).getValue()));
                }
            });

            edit_content.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean isFocus) {
                    if (!isEdit) return;
                    if (isFocus) {
                        edit_content.addTextChangedListener(mTextWatcher);
                    } else {
                        edit_content.removeTextChangedListener(mTextWatcher);
                    }
                }
            });

            if(divider_magin_right > 0 || divider_magin_left > 0){
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) img_divider_hor.getLayoutParams();
                layoutParams.setMargins(divider_magin_left,0,divider_magin_right,0);
                img_divider_hor.setLayoutParams(layoutParams);
            }
        }

        public void bind(int position) {
            ParamsEditItemData data = mListBean.getList().get(position);
            if (data.isVisiable()) {
                list_item.setVisibility(View.VISIBLE);
            } else {
                list_item.setVisibility(View.GONE);
                return;
            }
            view_item_title_zone.setVisibility(View.GONE);
            view_edit_zone.setVisibility(View.GONE);
            view_text_zone.setVisibility(View.GONE);
            btn_switch.setVisibility(View.GONE);
            view_item_data_zone.setVisibility(View.VISIBLE);
            img_tag_edit.setVisibility(View.GONE);
            img_star_edit.setVisibility(View.GONE);
            view_big_name_zone.setVisibility(View.GONE);
            view_name_zone.setVisibility(View.VISIBLE);

            switch (data.getEdit_type()) {
                case ParamsEditItemData.EDIT_TYPE_TEXT:
                    view_text_zone.setVisibility(View.VISIBLE);
                    text_content.setText(data.getValue_STR());
                    img_tag.setVisibility(View.GONE);
                    break;
                case ParamsEditItemData.EDIT_TYPE_TIME:
                    view_text_zone.setVisibility(View.VISIBLE);
                    text_content.setText(data.getValue_STR());
                    img_tag.setVisibility(View.VISIBLE);
                    break;
                case ParamsEditItemData.EDIT_TYPE_EDIT:
                case ParamsEditItemData.EDIT_TYPE_EDIT_BIG_NAME:
                    view_edit_zone.setVisibility(View.VISIBLE);
                    edit_content.setInputType(data.getInputType_REAL());
                    if (data.getMax_length() > 0) {
                        edit_content.setFilters(new InputFilter[]{new InputFilter.LengthFilter(data.getMax_length())});
                    } else {
                        edit_content.setFilters(new InputFilter[]{});
                    }
                    edit_content.setText(data.getValue_STR());
                    edit_content.setHint(isEdit?data.getHint():"未维护");
                    if (data.getEdit_type() == ParamsEditItemData.EDIT_TYPE_EDIT_BIG_NAME) {
                        view_big_name_zone.setVisibility(View.VISIBLE);
                        view_name_zone.setVisibility(View.GONE);
                        text_name_big.setText(data.getName_STR());
                    }

//                        edit_content.addTextChangedListener();
                    break;
                case ParamsEditItemData.EDIT_TYPE_CHOOSE:
                case ParamsEditItemData.EDIT_TYPE_CHOOSE_RELATE:
                case ParamsEditItemData.EDIT_TYPE_PROVINCE:
                    view_text_zone.setVisibility(View.VISIBLE);
                    text_content.setText(data.getValue_STR());
                    img_tag.setVisibility(View.VISIBLE);
                    break;

                case ParamsEditItemData.EDIT_TYPE_BOOLEAN:
                    view_text_zone.setVisibility(View.INVISIBLE);
                    btn_switch.setVisibility(View.VISIBLE);
                    btn_switch.setTag(position);
//                        btn_switch.setChecked();
                    break;
                case ParamsEditItemData.EDIT_TYPE_TITLE:
                    view_item_title_zone.setVisibility(View.VISIBLE);
                    view_item_data_zone.setVisibility(View.GONE);
                    break;
                case ParamsEditItemData.EDIT_TYPE_EDIT_AND_CHOOSE:
                    view_edit_zone.setVisibility(View.VISIBLE);
                    edit_content.setInputType(data.getInputType_REAL());
                    edit_content.setText(data.getValue_STR());
//                            if (data.getMax_length() > 0) {
//                                edit_content.setFilters(new InputFilter[]{new InputFilter.LengthFilter(data.getMax_length())});
//                            } else {
//                                edit_content.setFilters(new InputFilter[]{});
//                            }
                    img_tag_edit.setVisibility(View.VISIBLE);
                    img_tag_edit.setTag(position);
//                        edit_content.addTextChangedListener();
                    break;
            }
            if (!isEdit) {
                ViewUtils.setEditTextEnable(false, edit_content);
                img_tag.setVisibility(View.GONE);
            } else {
                ViewUtils.setEditTextEnable(true, edit_content);
            }
            if (!TextUtils.isEmpty(data.getUnit())) {
                text_unit.setVisibility(View.VISIBLE);
                text_unit.setText(data.getUnit());
            } else {
                text_unit.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(data.getName_des())) {
                text_name_des.setVisibility(View.VISIBLE);
                text_name_des.setText(data.getName_des());
            } else {
                text_name_des.setVisibility(View.GONE);
            }

//                edit_content.setInputType(InputType.TYPE_CLASS_NUMBER);
            text_title.setText(data.getName_STR());
            text_name.setText(data.getName_STR());
            edit_content.setTag(R.id.img_tag, position);
            text_content.setHint(isEdit?data.getHint():"未维护");
            edit_content.setHint(isEdit?data.getHint():"未维护");
            view_text_zone.setTag(position);

            if (data.getEdit_type() == ParamsEditItemData.EDIT_TYPE_TIME) {
                text_content.setText(data.getTIME_STR());
            } else if (data.getEdit_type() == ParamsEditItemData.EDIT_TYPE_BOOLEAN) {
                text_content.setText("");
//                    BleLog.i("switch== " + data.getName()+"的value==="+data.getValue());
                btn_switch.setChecked(StringUtil.Str2Boolean(data.getValue()));
            }

            if(CheckUtils.isPhone(data.getValue())){
                img_icon_call.setVisibility(View.VISIBLE);
            }else {
                img_icon_call.setVisibility(View.GONE);
            }
            img_icon_call.setTag(position);

        }

        @OnClick(R.id.view_text_zone)
        void onItemClick(View view) {
            int position = (int) view.getTag();
            ParamsEditItemData data = mListBean.getList().get(position);
            if (data.getEdit_type() == ParamsEditItemData.EDIT_TYPE_CHOOSE || data.getEdit_type() == ParamsEditItemData.EDIT_TYPE_CHOOSE_RELATE) {
                if (!isEdit) {
                    return;
                }
                ViewUtils.hideInput(mContext);
                OptionsPickerView pickerView = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        mListBean.onChildItemChoose(position, data.getChoose_items().get(options1));
                        if (data.getEdit_type() == ParamsEditItemData.EDIT_TYPE_CHOOSE_RELATE) {
                            mListBean.checkVisiable();
                        }
                        stopChangeAndNofyDataSetChanged();
                    }
                })
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .build();
                pickerView.setPicker(data.getChooseListString());
                pickerView.show();
            } else if (data.getEdit_type() == ParamsEditItemData.EDIT_TYPE_TIME) {
                if (!isEdit) {
                    return;
                }
                ViewUtils.hideInput(mContext);
                Calendar calendar = Calendar.getInstance();
                if(!TextUtils.isEmpty(data.getValue())){
                    calendar.setTimeInMillis(Long.valueOf(data.getValue()));
                }
                TimePickerView pvTime = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
//                            String timeValue = TimeUtils.getTimeLongToStrByFormat(date.getTime(), "yyyy/MM/dd,HH:mm:ss");
                        String timeValue = date.getTime() + "";
                        mListBean.onChildItemChoose(position, timeValue, timeValue);
                        stopChangeAndNofyDataSetChanged();
                    }
                })
                        .setType(data.getListTimeBoolean())// 默认全部显示
                        .setDate(calendar)
                        .build();
                pvTime.show();
            }else if (data.getEdit_type() == ParamsEditItemData.EDIT_TYPE_PROVINCE) {
                if (!isEdit) {
                    return;
                }
                ViewUtils.hideInput(mContext);

                ProvinceListBean provinceListBean = new ProvinceListBean();
                provinceListBean = (ProvinceListBean) provinceListBean.getObjFromCache();
                if(provinceListBean == null){
                    LogUtil.i("省份数据不存在");
                    return;
                }

                ArrayList<String> options1Items =provinceListBean.getListStr();
                ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
                for(int i = 0,l = options1Items.size(); i < l ; i ++){
                    options2Items.add(provinceListBean.getList().get(i).getListStr());
                }

                int seletedOne = 0;
                int seletedTwo = 0;
                if(!TextUtils.isEmpty(data.getValue())){
                    String[] strs = data.getValue().split(" ");
                    if(strs != null && strs.length == 2){
                        seletedOne = provinceListBean.getSeletedProvincePosition(strs[0]);
                        seletedTwo = provinceListBean.getSeletedCityPosition(strs[0],strs[1]);
                    }
                }

                OptionsPickerView pvOptions = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        String opt1tx = options1Items.size() > 0 ?
                                options1Items.get(options1) : "";

                        String opt2tx = options2Items.size() > 0
                                && options2Items.get(options1).size() > 0 ?
                                options2Items.get(options1).get(options2) : "";

                        String tx = opt1tx+" "+opt2tx ;
                        LogUtil.i("选择了---》"+tx);
//                        String result =  opt1tx+" "+opt2tx ;
                        mListBean.onChildItemChoose(position, tx, tx);
                        isStopChange = true;
                        notifyDataSetChanged();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                isStopChange = false;
                            }
                        }, 500);
                    }
                })

                        .setTitleText(data.getHint())
                        .setSelectOptions(seletedOne,seletedTwo)
                        .setDividerColor(Color.BLACK)
                        .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                        .setContentTextSize(20)
                        .build();
                pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
//                pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
                pvOptions.show();
            }

            //结尾
        }

        @OnClick(R.id.img_icon_call)
        void onImgCallClick(View view){
            int position = (int) view.getTag();
            ParamsEditItemData data = mListBean.getList().get(position);
            if(CheckUtils.isPhone(data.getValue())){
                IntentUtils.callToDial(mContext,data.getValue());
            }
        }

        TextWatcher mTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (isStopChange) return;
                if (edit_content.getTag(R.id.img_tag) == null) return;
//                                int position = (int) edit_content.getTag(R.id.img_tag);
                int position = getAdapterPosition();
//                        LogUtil.i("afterTextChanged--->" + position + "----内容---》" + editable.toString());
//                        LogUtil.i("afterTextChanged--->" + position + "----内容---》" + edit_content.getText().toString());
                mListBean.setEditChange(position, edit_content.getText().toString());
            }
        };


        @OnClick(R.id.img_tag_edit)
        void onImgTagEditClick(View view) {
            int position = (int) view.getTag();
            ParamsEditItemData data = mListBean.getList().get(position);
            if (data.getEdit_type() != ParamsEditItemData.EDIT_TYPE_EDIT_AND_CHOOSE) return;
            if (!isEdit) {
                return;
            }
            ViewUtils.hideInput(mContext);
            OptionsPickerView pickerView = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    mListBean.onChildItemChoose(position, data.getChoose_items().get(options1));
                    stopChangeAndNofyDataSetChanged();
                }
            })
                    .setSubmitText("确定")//确定按钮文字
                    .setCancelText("取消")//取消按钮文字
                    .build();
            pickerView.setPicker(data.getChooseListString());
            pickerView.show();
        }

        void stopChangeAndNofyDataSetChanged() {
            //防止跟edittext的变化监听冲突而设置的缓冲时间
            isStopChange = true;
            notifyDataSetChanged();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    isStopChange = false;
                }
            }, 1000);
        }

    }

}
